package com.wangge.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;

public class Period implements Serializable {
  private static final long serialVersionUID = -2072208249014270392L;
  private final Date start;
  private final Date end;
  
  public Period(Date start, Date end) {
    super();
    this.start = new Date(start.getTime());
    this.end = new Date(end.getTime());
  }
  
  public Date getStart() {
    return new Date(this.start.getTime());
  }
  
  public Date getEnd() {
    return new Date(this.end.getTime());
  }
  
  private Object writeReplace() {
    return new SerializationProxy(this);
  }
  
  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
    throw new InvalidObjectException("Proxy required");
  }
  
  @Override
  public String toString() {
    return "Period [start=" + start + ", end=" + end + "]";
  }
  
  private static class SerializationProxy implements Serializable {
    private static final long serialVersionUID = -2072208249014270314L;
    private final Date start;
    private final Date end;
    
    SerializationProxy(Period p) {
      this.start = p.start;
      this.end = p.end;
    }
    
    private Object readResolve() {
      return new Period(start, end);
    }
  }
  
  public static void main(String[] args) {
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream out = new ObjectOutputStream(bos);
      out.writeObject(new Period(new Date(), new Date()));      
      byte[] ref = { 0x71, 0, 0x70, 0, 5 };
      bos.write(ref);
      ref[4] = 4;
      bos.write(ref);
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
      Object period = in.readObject();
      System.out.println(period);
      Object ob = in.read();
      System.out.println(ob);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    
  }
}
